import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {Button, Input, Spin, Form, Row, Col, Select, Upload, Icon, Radio, Card, Modal, message} from 'antd';
import 'braft-editor/dist/index.css';
import BraftEditor from 'braft-editor';
import { routerRedux } from 'dva/router';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { bfUploadFn } from '@/utils/utils';
import {LZFormItem} from "@/components/LZForm";
import {uploadUrl} from "@/config";
import commonApi from '@/services/common'
import TribeApi from '@/services/tribe'
import { getToken } from "@/utils/localStorage";
import {isEqual} from "lodash";
import RouterWillLeave from "@/components/RouterWillLeave";


const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 3,
  },
  wrapperCol: {
    span: 21,
  },
};
@connect()
@Form.create()
class Publish extends PureComponent {
  
  state = {
    imgSrc: '',
    picUrl: '',
    platforms: [],
    detail: {},
    imgVisible: false,
    updateId: 0,
    fileList: [],
    id: '',
    images: [],
    isSubmit: false,
    originValues: {},
  }
  
  componentDidMount() {
    const {
      match: {
        params: { id },
      },
    } = this.props;
    this.getPlatformChannel()
    this.handleSetOriginValues()
    if (id) {
      this.getDetail(id)
    }
  }
  
  handleSetOriginValues = () => {
    const values = this.props.form.getFieldsValue()
    this.setState({
      originValues: values,
    });
  }
  
  getPlatformChannel = () => {
    commonApi.selectPlateformChannel().then(res=>{
      this.setState({
        platforms: res
      });
    })
  }
  
  getDetail = (id) => {
    TribeApi.queryTribeDetail({
      id
    }).then(res=>{
      this.props.form.setFieldsValue({
        content: BraftEditor.createEditorState(res.content)
      })
      const fileList = res.images && res.images.map(image=>({uid: image.src, url: image.src})) || []
      this.setState({
        detail: res,
        fileList,
        id
      });
      this.handleSetOriginValues()
    })
  }

  handleSubmit = e => {
    const { form, dispatch } = this.props;
    const {id, images, detail} = this.state
    e.preventDefault();
    form.validateFields((err, fieldsValue) => {
      const obj = {
        name: fieldsValue.name,
        content: fieldsValue.content.toHTML(),
      };
      if (id) {
        obj.id = Number(id);
      }
      if (err) {
        message.error('存在未输入的必填项')
        return
      };
      this.setState({
        isSubmit: true
      });
      let service = TribeApi.addTribe;
      if (this.state.id) {
        service = TribeApi.modifyTribe
      }
      service({
        ...fieldsValue,
        ...obj,
        images: images.length ? images : detail.images,
        picUrl: this.state.picUrl,
      }).then(res => {
        message.success('操作成功')
        this.handleCancel();
      })
    });
  };

  handleCancel = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push('/configure/tribe'));
  };
  
  handleChangeInitialValue = (evt, field) => {
    this.setState({
      detail: {
        ...this.state.detail,
        [field]: evt.target.value
      }
    });
  }
  
  handleUploadChange = ({ file, fileList, event }, type) => {
    const _fileList = [...fileList] || [];
    if (type === 'picUrl') {
      if (file.status === 'done') {
        _fileList.map(item=>{
          this.setState({
            picUrl: item.response.data,
          });
        })
        this.setState({
          picUrl: file.response.data,
        });
      }
    } else {
      if (file.status === 'done') {
        const images = _fileList.map(f=>{
          return 	{
            "isMain": 0,
            "src": f.response.data
          }
        })
        this.setState({
          images,
        });
      }
      this.setState({
        fileList: _fileList,
      });
    }
  }
  
  // 上传后预览的回调
  handlePreview = () => {
    this.setState({
      imgVisible: true,
    });
  }

  handleImgCancel = () => {
    this.setState({
      imgVisible: false,
    });
  };
  
  // 上传后删除的回调
  onRemove = (type) => {
    if (type === 'picUrl') {
      this.setState({
        picUrl: ''
      });
    } else {
      this.setState(
        {
          fileList: [],
          imgSrc: '',
        })
    }
  }
  
  renderRouterWillLeave=()=>{
    const values = this.props.form.getFieldsValue()
    
    const { originValues, isSubmit } = this.state
    const isPrompt = !isEqual(values, originValues)
    console.log(isPrompt, values, originValues);
    return (
      <RouterWillLeave isPrompt={isPrompt} isSubmit={isSubmit}  />
    )
  }
  
  render() {
    const {form: { getFieldDecorator }} = this.props;
    const {imgSrc, fileList, platforms, detail, imgVisible} = this.state
    const {title, summary, channerIds, content, viewCount, top = 1,
      commentCount, picUrl, status = true, images} = detail
    const checkContent = (_, value, callback) => {
      if (value.toHTML() === '<p></p>') {
        callback('请输入部落内容');
        return;
      }
      callback();
    };
    const checkMainImages = (_, value, callback) => {
      if (!value) {
        callback('请上传图片');
        return;
      }
      callback();
    };
    
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传照片</div>
      </div>
    )
  
    const renderPic = () => {
      if (this.state.picUrl) {
        return (
          <img src={this.state.picUrl} style={{ width: 100, height: 100 }} alt="" />
        )
      } if (this.state.detail.picUrl) {
        return (
          <img src={this.state.detail.picUrl} style={{ width: 100, height: 100 }} alt="" />
        )
      }
        return uploadButton
      
    }
    
    return (
      <PageHeaderWrapper title="发布图文">
        {
          this.renderRouterWillLeave()
        }
        <Spin spinning={false}>
          <Card bordered={false}>
            <Form {...formItemLayout}>
              <LZFormItem label="上架渠道" field="channerIds" getFieldDecorator={getFieldDecorator}
                          requiredMessage="上架渠道不能为空"
                          initialValue={channerIds || []}>
                <Select
                  mode="multiple"
                  style={{ width: '100%' }}
                  placeholder="请选择"
                >
                  {
                    platforms.map((item, sign) => {
                      return (
                        <Select.Option key={item.appId} value={item.channelId}>
                          {item.channelName}
                        </Select.Option>
                      )
                    })
                  }
                </Select>
              </LZFormItem>
              <LZFormItem label="部落标题" field="title" getFieldDecorator={getFieldDecorator}
                          requiredMessage="部落标题不能为空" initialValue={title} >
                <Input placeholder="请输入" />
              </LZFormItem>
              <LZFormItem label="摘要" field="summary" getFieldDecorator={getFieldDecorator}
                          requiredMessage="摘要不能为空" initialValue={summary}>
                <Input.TextArea rows={4} placeholder="请输入摘要" />
              </LZFormItem>
              <LZFormItem label="部落内容" field="content" getFieldDecorator={getFieldDecorator}
                          requiredMessage="部落内容不能为空" rules={[{ validator: checkContent }]}
                          initialValue={BraftEditor.createEditorState(content)}>
                <BraftEditor
                  style={{ border: '1px solid #d1d1d1', borderRadius: 5, backgroundColor: '#fff' }}
                  contentStyle={{ height: 500, boxShadow: 'inset 0 1px 3px rgba(0,0,0,.1)' }}
                  excludeControls={['emoji', 'clear', 'blockquote', 'code']}
                  media={{ uploadFn: bfUploadFn }}
                />
              </LZFormItem>
             
              <Form.Item label="初始值" required>
                <LZFormItem field="viewCount" getFieldDecorator={getFieldDecorator}
                            requiredMessage="查看人数初始值不能为空" initialValue={viewCount}
                onChange={(evt)=>this.handleChangeInitialValue(evt, 'viewCount')}>
                  <div className="single-row">
                    查看人数初始值<Input placeholder="请输入" value={viewCount} />人
                  </div>
                </LZFormItem>
                <LZFormItem field="commentCount" getFieldDecorator={getFieldDecorator}
                            requiredMessage="跟帖人数初始值不能为空" initialValue={commentCount}
                            onChange={(evt)=>this.handleChangeInitialValue(evt, 'commentCount')}>
                  <div className="single-row">
                    跟帖人数初始值<Input placeholder="请输入" value={commentCount} />人
                  </div>
      
                </LZFormItem>
                <LZFormItem field="top" getFieldDecorator={getFieldDecorator}
                            requiredMessage="top初始值不能为空" initialValue={top}
                            onChange={(evt)=>this.handleChangeInitialValue(evt, 'top')}>
                  <div className="single-row">
                    top初始值<Input placeholder="请输入" value={top} />
                  </div>
                </LZFormItem>
              </Form.Item>
              <Form.Item label="封面图片" required>
                {getFieldDecorator('picUrl', {
                  rules: [{ validator: checkMainImages }],
                  initialValue: picUrl,
                })(
                  <div className="upload-desc">
                    <Upload
                      accept="image/*"
                      action={uploadUrl}
                      headers={{
                        token: getToken()
                      }}
                      showUploadList={false}
                      listType="picture-card"
                      onPreview={this.handlePreview} // 预览
                      onRemove={()=>this.onRemove('picUrl')} // 删除
                      onChange={(evt)=>this.handleUploadChange(evt, 'picUrl')}
                    >
                      {renderPic()}
                    </Upload>
                    <div className="size-desc">
                      建议尺寸： 340px*330px
                    </div>
                  </div>
                 
                )}
              </Form.Item>
              <Form.Item label="详情轮播图片">
                {getFieldDecorator('images', {
                  rules: [
                    {
                      validator: (rule, value, callback) => {
                        if (!value) {
                          callback('详情轮播图片不能为空');
                        }
                        callback();
                      },
                    },
                  ],
                  initialValue: images || null,
                })(
                  <div className="upload-desc flex-column">
                    <Upload
                      accept="image/*"
                      action={uploadUrl}
                      headers={{
                        token: getToken()
                      }}
                      listType="picture-card"
                      fileList={fileList}
                      onPreview={this.handlePreview} // 预览
                      onChange={this.handleUploadChange}
                    >
                      {uploadButton}
                    </Upload>
                    <div className="size-desc">建议尺寸：750px*500px</div>
                  </div>
                )}
              </Form.Item>
              <LZFormItem label="状态" field="status" required
                          getFieldDecorator={getFieldDecorator} initialValue={status}>
                <Radio.Group>
                  <Radio value="VALID">有效</Radio>
                  <Radio value="INVALID">无效</Radio>
                </Radio.Group>
              </LZFormItem>
    
              <FormItem>
                <Row>
                  <Col span={24} style={{ textAlign: 'center' }}>
                    <Button style={{ marginLeft: 8 }} onClick={this.handleCancel}>
                      取消
                    </Button>
                    <Button type="primary" htmlType="submit" onClick={this.handleSubmit}>
                      确定
                    </Button>
                  </Col>
                </Row>
              </FormItem>
            </Form>
          </Card>
        </Spin>
        <Modal visible={imgVisible} footer={null} onCancel={this.handleImgCancel} width={600}>
          <img src={imgSrc || null} alt="" style={{ width: '100%', paddingTop: 15 }} />
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
export default Publish;
